package com.xiaou.realm;

import java.util.HashMap;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.http.HttpRequest;

import com.google.code.kaptcha.Constants;
import com.xiaou.utils.GeetestConfig;
import com.xiaou.utils.GeetestLib;
/**
 * 自定义过滤器
 * @author xiaou
 *
 */
public class VerificationCodeAuthenticationFilter extends FormAuthenticationFilter{

	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		HttpServletRequest req = (HttpServletRequest) request;
		String uri = req.getRequestURI();
		System.out.println(uri);
		// 判断是否是登陆请求
		if("/login".equals(uri)) {
			String vCode = request.getParameter("VerificationCode");
			if(null != vCode && !"".equals(vCode)) {
				String sessionCode = (String) req.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
				
				if(!vCode.equalsIgnoreCase(sessionCode)) {
					request.setAttribute("vCode", "验证码验证失败");
					return true;
				}
			}
		}
		
		// 滑块的验证
		GeetestLib gtSdk = new GeetestLib(GeetestConfig.getGeetest_id(), GeetestConfig.getGeetest_key(),
                GeetestConfig.isnewfailback());
        String challenge = req.getParameter(GeetestLib.fn_geetest_challenge);
        String validate = req.getParameter(GeetestLib.fn_geetest_validate);
        String seccode = req.getParameter(GeetestLib.fn_geetest_seccode);
        //从session中获取gt-server状态
        int gt_server_status_code = (Integer) req.getSession().getAttribute(gtSdk.gtServerStatusSessionKey);
        //从session中获取userid
        String userid = (String)req.getSession().getAttribute("userid");
        //自定义参数,可选择添加
        HashMap<String, String> param = new HashMap<String, String>();
        param.put("user_id", userid); //网站用户id
        param.put("client_type", "web"); //web:电脑上的浏览器；h5:手机上的浏览器，包括移动应用内完全内置的web_view；native：通过原生SDK植入APP应用的方式
        param.put("ip_address", request.getRemoteAddr()); //传输用户请求验证时所携带的IP
        int gtResult = 0;
        if (gt_server_status_code == 1) {
            //gt-server正常，向gt-server进行二次验证
            gtResult = gtSdk.enhencedValidateRequest(challenge, validate, seccode, param);
            System.out.println("gt-server正常，验证结果："+gtResult+"");
        } else {
            // gt-server非正常情况下，进行failback模式验证
            System.out.println("failback:use your own server captcha validate");
            gtResult = gtSdk.failbackValidateRequest(challenge, validate, seccode);
            System.out.println("gt-server非正常情况下，验证结果："+gtResult+"");
        }
        if (gtResult == 1) {
            // 验证成功
        	return true;
        }
        else {
            // 验证失败
        	request.setAttribute("vCode", "登陆出现异常");
        	return true;
        }
		
	}
}
